import { createWebHistory, createRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const routes = [
    { path: '/', redirect: '/layout' },// 路由重定向
    {
        path: '/layout',
        name: 'layout',
        component: () => import('../view/layout/index.vue'),
        redirect: '/home',
        children: [
            {
                path: '/home',
                name: 'home',
                component: () => import('../view/home/index.vue'),
                meta: { title: '首页' }
            },
            {
                path: '/role',
                name: 'role',
                component: () => import('../view/role/index.vue'),
                meta: { title: '角色管理' }
            },
            {
                path: '/user',
                name: 'user',
                component: () => import('../view/user/index.vue'),
                meta: { title: '用户管理' }
            },
            {
                path: '/menu',
                name: 'menu',
                component: () => import('../view/menu/index.vue'),
                meta: { title: '菜单管理' }
            },
            {
                path: '/other',
                name: 'other',
                component: () => import('../view/other/index.vue'),
                meta: { title: '其他页面' }
            },
        ]
    },
    {

        path: '/login',
        name: 'login',
        component: () => import('../view/login/index.vue')
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    const token = localStorage.getItem('viteToken')

    // 1. 未登录状态
    if (!token) {
        if (to.path === '/login') {
            return next() // 允许访问登录页
        } else {
            ElMessage.error('请先登录')
            return next('/login') // 重定向到登录页
        }
    }

    // 2. 已登录状态
    if (to.path === '/login') {
        ElMessage.success('您已登录，将跳转到首页')
        return next('/layout') // 重定向到首页
    }

    // 3. 其他情况正常放行
    next()
})
export default router
